package examples;
import pizza.util.*;
class Tree {
case Leaf(a elem);
case Branch(Tree l, Tree r);
}
class DelayedEnumerator extends Enumerator {
()->Enumerator susp;
Enumerator value = null;
public DelayedEnumerator(()->Enumerator susp) {
this.susp = susp;
}
private Enumerator force() {
if (value == null) value = susp();
return value;
}
public boolean hasMoreElements() {
return force().hasMoreElements();
}
public A nextElement() {
return force().nextElement();
}
}
class SameFringe{
static Enumerator fringe(Tree t) {
return new DelayedEnumerator(
fun()->Enumerator {
switch (t) {
case Leaf(A elem):
return new SingletonEnumerator(elem);
case Branch(Tree l, Tree r):
return fringe(l).concat(fringe(r));
}});
}
static boolean sameFringe(Tree t1, Tree t2) {
Enumerator fringe1 = fringe(t1);
Enumerator fringe2 = fringe(t2);
while (fringe1.hasMoreElements() &&
fringe2.hasMoreElements() &&
fringe1.nextElement().equals(fringe2.nextElement()));
return !fringe1.hasMoreElements() && !fringe2.hasMoreElements();
}
static public void main(String[] argv) {
System.out.println(
sameFringe(
new Branch(
new Leaf("A"),
new Branch(new Leaf("B"), new Leaf("C"))),
new Branch(
new Branch(
new Leaf("A"), new Leaf("B")),
new Leaf("C"))));
System.out.println(
sameFringe(
new Branch(
new Leaf(new Integer(1)),
new Leaf(new Integer(2))),
new Leaf(new Integer(1))));
}
}